package com.bnd.common.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * PostgreSQL text[] 与 List<String> 互转的 TypeHandler
 * 中文说明：用于处理 MyBatis / MyBatis-Plus 在插入和查询时对数组类型的映射
 */
@MappedJdbcTypes(JdbcType.ARRAY)
@MappedTypes(List.class)
public class PgTextArrayTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        Connection connection = ps.getConnection();
        Array array = connection.createArrayOf("text", parameter.toArray(new String[0]));
        ps.setArray(i, array);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Array array = rs.getArray(columnName);
        return convert(array);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Array array = rs.getArray(columnIndex);
        return convert(array);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Array array = cs.getArray(columnIndex);
        return convert(array);
    }

    private List<String> convert(Array array) throws SQLException {
        if (array == null) {
            return new ArrayList<>();
        }
        Object arr = array.getArray();
        if (arr instanceof String[] sa) {
            return Arrays.asList(sa);
        }
        // 兜底：驱动返回 Object[]
        Object[] oa = (Object[]) arr;
        List<String> list = new ArrayList<>(oa.length);
        for (Object o : oa) {
            list.add(o == null ? null : o.toString());
        }
        return list;
    }
}


